/*
 * Copyright 2009 (c) Patrick Pietens.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
package indigo.service.services 
{
	import indigo.service.errors.ServiceError;
	import indigo.service.events.ServiceEvent;
	import indigo.utils.DisposableEventDispatcher;

	import flash.events.Event;
	import flash.net.NetConnection;
	import flash.net.Responder;

	/**
	 * Executes when the Service responds successfully
	 */
	[Event(name="serviceResult", type="indigo.events.ServiceEvent")]

	/**
	 * Executes when the Service responds with an error
	 */
	[Event(name="serviceFault", type="indigo.events.ServiceEvent")]	
	/**
	 * The AMFService class is used to send an load data to an AMF remote service. 
	 * It is recommend to use the sendAndLoadAMF shortcut. 
	 * 
	 */
	public class AMFService extends DisposableEventDispatcher implements IService
	{
		/**
		 * NetConnection that is used to execute the IService
		 */
		protected var _connection:NetConnection;
		/**
		 * String that indicates the post method of the IService
		 */
		protected var _method:String;		 

		
		/**
		 * AMFService
		 * @param	Location of the service
		 * @param	Service to execute
		 * @param	ObjectEncoding used to connect to the IService
		 * 
		 */
		public function AMFService( gateway:String, method:String = null, objectEncoding:uint = 0 )
		{
			// Create a connection to the IService gateway
			this._connection = new NetConnection( );
			this._connection.objectEncoding = objectEncoding;
			this._connection.connect( gateway );
			
			this._method = method;
		}

		
		/**
		 * Executes the IService
		 * @param	[optional] Arguments send to the IService
		 * 
		 */
		public function sendAndLoad( ...args ):void
		{
			// Prepare the service call
			var myResponder:Responder = new Responder( this.onResult, this.onFault );
			var myArguments:Array = [ this._method, myResponder ];
			myArguments = myArguments.concat( args );

			// Make the remote call
			this._connection.call.apply( this._connection, myArguments );
		}

		
		/**
		 * Executes when the IService responds succesfully
		 * @param	Result of the call
		 * 
		 */		
		protected function onResult( data:Object ):void
		{
			// Dispatch event
			if ( this.hasEventListener( ServiceEvent.RESULT ) )
			{			
				var myEvent:ServiceEvent = new ServiceEvent( ServiceEvent.RESULT );
				myEvent.data = data;
				this.dispatchEvent( myEvent );
			}
			
			this.dispose( );
		}

		
		/**
		 * Executes when an error occured while executing the IService
		 * @param	Object containing  information about the error
		 * 
		 */		
		protected function onFault( info:Object ):void
		{
			if ( this.hasEventListener( ServiceEvent.FAULT ) )
			{
				var myEvent:ServiceEvent = new ServiceEvent( ServiceEvent.FAULT );
				myEvent.errorCode = info.toString( );
				this.dispatchEvent( myEvent );
			}
			else
				throw new ServiceError( ServiceError.SERVICE_EXCEPTION + ": " + info );
		}

		
		/**
		 * Integer that indicates the object encoding of the service
		 *
		 */
		public function set objectEncoding( value:int ):void 
		{
			this._connection.objectEncoding = value;
		}

		
		/**
		 * Integer that indicates the object encoding of the service
		 * 
		 */
		public function get objectEncoding():int 
		{
			return this._connection.objectEncoding;
		}		

		
		/**
		 * String that indicates the destination of the service
		 *
		 */
		public function set destination( value:String ):void 
		{
			this._method = value;
		}

		
		/**
		 * String that indicates the destination of the service
		 * 
		 */
		public function get destination():String 
		{
			return this._method;
		}

		
		/**
		 * NetConnection that is used to execute the IService
		 * 
		 */		
		public function get connection():NetConnection
		{
			return this._connection;
		}

		
		/**
		 * Disposes the AMFService
		 * 
		 */
		override public function dispose( event:Event = null ):void
		{
			super.dispose( event );
			
			this._connection.close( );
			
			// nullify objects
			this._connection = null;
			this._method = null;							
		}		
	}
}